package com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow;

import android.app.Activity;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fuqi.android.zhongcai.utils.dic.impl.Field;
import com.fuqi.android.zhongcai.utils.dic.impl.FieldConstant;
import com.fuqi.android.zhongcai.utils.dic.impl.Table;

import java.util.List;


public class CustomListAdapter extends BaseAdapter implements OnClickListener {
	private Activity activity;
	private LayoutInflater inflater;
	private ARResponse response=new ARResponse();
	private Table table=new Table();

	private List<Field> fields;
//	private CJPopupWindow manage; // popupwindow管理类
//	private CJRowCompsFactory factory; // popupwindow中组件工厂类
	private int index = -1; // 选中项下标
	private int layoutID;
	protected int[] mTo; // 第一列展示列，第二列展示值
	protected CJRowListener seedListener;
	protected ViewBinder mViewBinder;
	protected ViewBinder mLableBinder;

	public CustomListAdapter(Activity activiay,  Table table, ARResponse response) {
		try {
			this.activity = activiay;
			this.inflater = LayoutInflater.from(activiay);
			this.table = table;
			this.response = response;
			this.fields = this.table.getFieldList();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public CustomListAdapter(Activity activiay,  Table table, ARResponse response,
							 int layoutID, int[] to) {
		this(activiay,  table, response);
		this.layoutID = layoutID;
		this.mTo = to;
	}

	public void setCJRowListener(CJRowListener seedListener) {
		this.seedListener = seedListener;
	}

	public void refresh(ARResponse response){
		this.response = response;
		notifyDataSetChanged();
	}

	public void setViewBinder(ViewBinder binder) {
		this.mViewBinder = binder;
	}
	
	public void setLableBinder(ViewBinder binder){
		this.mLableBinder = binder;
	}

	public int getCount() {
		if (fields != null) {
			/*int i = 0;
			for (Field f : fields) {
				if (f.canShow())
					i++;
			}*/
			return fields.size();
		}else
			return 0;
	}
	

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	/**
	 * 画列表的项，根据下标iIndex判断选中项与普通项并赋值
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = createViewFromResource(position, convertView, parent, layoutID);
		return v;
	}

	protected View createViewFromResource(int position, View convertView,
			ViewGroup parent, int resource) {
		View v = inflater.inflate(resource, parent, false);

		bindView(position, v);
		
		v.setOnClickListener(this);
		
		return v;
	}
	
	// 绑定一项（一项包含键和值）
	private void bindView(int position, View view) {
		Field field = fields.get(position);
		boolean canshow = field.canShow();

		if(!canshow){
			view.setVisibility(View.GONE);
			return;
		}
		
		bindLable(position, view, field);
		bindValue(position, view, field);
		view.setTag(field);
	}

	// 绑定键列
	private void bindLable(int position, View view, Field field) {
		if (mLableBinder != null) {
			boolean bound = mLableBinder.setViewValue(view, field.getLabel(), position,
					field.getFieldName());
			
			if(bound) return;
		}
		final View v = view.findViewById(mTo[0]);
		if (v instanceof TextView) {
			setViewText((TextView) v, field.getLabel());
		}else if(v instanceof ImageView){
			setViewImage((ImageView) v, field.getLabel());
		}

	}

	private boolean isloaded = false;

	// 绑定值列
	private void bindValue(final int position, final View view,
			final Field field) {

		if (response == null) {
			isloaded = false;
			return;
		}
		// 没有数据
		if (response.getRowNum() == 0) {
			// TODO 加效果
			isloaded = false;
			((TextView) view.findViewById(mTo[1])).setText("请稍后...");
			return;
		}
		isloaded = true;
		final View v = view.findViewById(mTo[1]);
		ViewBinder binder = mViewBinder;

		// 对应的数据字典
		int functionNo = field.getFunctionNo();
		String content = "";

		if (functionNo < 0) {
			content = response.getValue(field.getFieldName());
		} else {
			content = getValueByField(response.getValue(field.getFieldName()),
					field);
		}
		content = content == null ? "" : content.toString();
		// 是否为可编辑状态
		boolean editable = field.isEditable();
		// 显示类型
		int showtype = field.getShowType();
		// 输入类型
		int inputtype = field.getInputType();
		if (!editable) { // 不可编辑
			((TextView) v).setText(content);
			if (inputtype == FieldConstant.INPUTTYPE_SINGLE) {
				((TextView) v).setSingleLine(true);
			} else if (inputtype == FieldConstant.INPUTTYPE_MULTIPLE) {
				((TextView) v).setSingleLine(false);
			}
		} else if (showtype == FieldConstant.SHOWTYPE_JUMP_ACTIVITY) { // 可编辑但不在本页面，跳ACTIVITY方式
			if (content.equals(""))
				if(field.getLabel() !=null && field.getLabel().length() <= 6)
					((TextView) v).setText("请选择" + field.getLabel());
				else
					((TextView) v).setText("请选择");
			else
				((TextView) v).setText(content);
			
			ImageView iv = new ImageView(activity);
			RelativeLayout.LayoutParams layoutparams = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
			layoutparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			layoutparams.rightMargin = 10;
			iv.setLayoutParams(layoutparams);
			iv.setScaleType(ScaleType.CENTER_INSIDE);
			((RelativeLayout) view).addView(iv);
		} else if (showtype != 0) { // 可编辑，弹POPUPWINDOW方式 或 页面编辑
			((TextView) v).setText(content);
			if(field.getLabel() !=null && field.getLabel().length() <= 6)
				((TextView) v).setHint("请输入" + field.getLabel());
			else
				((TextView) v).setHint("请输入");
		} else { // 按输入类型NEW出不同类型的控件
			View seed = null;
			if (inputtype == FieldConstant.INPUTTYPE_UNKNOWN) {
				
			}else if (inputtype == FieldConstant.INPUTTYPE_NOCHANGE) {
					
			}else if (inputtype == FieldConstant.INPUTTYPE_SINGLE) {

			} else if (inputtype == FieldConstant.INPUTTYPE_RADIO) {
				/*((ViewGroup)view).removeViewInLayout(v);
				v.setVisibility(View.GONE);
				RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams) v
						.getLayoutParams();

				seed = new CJSexChoose(activity,
						StringUtil.parseInt(content));
				layoutparams.width = LayoutParams.FILL_PARENT;
				seed.setLayoutParams(layoutparams);
				seed.setTag(position);
				seed.setId(v.getId());
				((CJSexChoose) seed)
						.setOnChooseListener(new ChooseListener() {

							@Override
							public void onChoosed(int checked, View v) {
								index = StringUtil.parseInt(v.getTag()
										.toString());
								setFieldvalue(index, checked + "");
							}
						});
*/
			} 
				// TODO 内部添加其他类型（也可以在通过外部设定绑定器绑定）
			if (seed != null) ((RelativeLayout) view).addView(seed);
		}
		

		// 用外部设定的绑定器绑定
		if (binder != null) {
			binder.setViewValue(view, content, position,
					field.getFieldName());
		}
	}

	private void setViewImage(ImageView v, String value) {
		try {
			v.setImageResource(Integer.parseInt(value));
		} catch (NumberFormatException nfe) {
			v.setImageURI(Uri.parse(value));
		}
	}

	private void setViewText(TextView v, String text) {
		v.setText(text);
	}

	@Override
	public void onClick(View v) {
		if (!isloaded) return;
		Field field = (Field) ((v).getTag());
		int showtype = field.getShowType();
		index = fields.indexOf(field);
		v.setFocusable(true);
		v.setFocusableInTouchMode(true);
		v.requestFocus();
		switch (showtype) { // 0: 无点击即显示 1:点击后当前页面编辑 2：点击后跳转activity
							// 3:点击后跳转popupWindow
		case 1:
			if (seedListener != null)
				if (seedListener.seedAction(index,field, response.getValue(fields.get(index).getFieldName()))) return;
			break;
		case 2:
			if (seedListener != null)
				if (seedListener.activityAction(field, response.getValue(fields.get(index).getFieldName()))) return;
			break;
		case 3:
//			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			if (seedListener != null)
				if (seedListener.popupWindowAction(field, response.getValue(fields.get(index).getFieldName()))) break;
			/*
			if(field.getInputType() == 7 || field.getInputType() == 8)
				makePopupWindowByField(field, mainHander).showAtLocation(v,
					Gravity.BOTTOM, 0, 0);
			else
				makePopupWindowByField(field, mainHander).showAtLocation(v,
						Gravity.CENTER, 10, 10);
			break;*/
			break;
		default:
			// Toast.makeText(activity, "Click on---->" + index + "项",
			// Toast.LENGTH_LONG).show();
			break;
		}
	}


	private String getValueByField(String id, Field field) {
		String showValue = id;
		/*ARResponse response = EnumerationManager.getValueFieldResponseByID(
				activity, id, field);
		if (response != null && response.next()) {
			showValue = response.getValue(1);
		}*/
		return showValue;
	}



}
